package com.springx.examples.showcase.common.spring.token;
import java.lang.reflect.Method;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
/**
 * 禁止表单重复提交拦截器
 *
 * @author DigitalSonic
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {
	/** 错误消息 */
	private static final String ERROR_MESSAGE = "Bad or missing token!";
	@Autowired
    private FormManager formManager;
    
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception {
    	boolean flag = true;
    	if(handler instanceof HandlerMethod){
			HandlerMethod handlerMethod=(HandlerMethod)handler;
			Method method=handlerMethod.getMethod();
			Token annotation=method.getAnnotation(Token.class);
			if(annotation!=null&&annotation.value()==TokenType.CREATE){
				   Form form=formManager.createForm(request);
				   request.setAttribute(Form.FORM_TOKEN_FIELD_NAME, form.getToken());
			}else if(annotation!=null&&annotation.value()==TokenType.VALID){
				    String token = request.getParameter(Form.FORM_TOKEN_FIELD_NAME);
			        if (token != null) {
			            if (formManager.hasForm(request, token)) {
			                formManager.removeToken(request, token);
			            } else {
			            	flag = false;
			            }
			        }
			        if(!flag){
		        	    String requestType = request.getHeader("X-Requested-With");
		                if (requestType != null && requestType.equalsIgnoreCase("XMLHttpRequest")){
		                	response.addHeader("tokenStatus", "accessDenied");
		                }else{
		                	response.sendError(HttpServletResponse.SC_FORBIDDEN, ERROR_MESSAGE);
		                }
			        }
			}
		}
        return flag;
    }
   
}